package me.shurufa.share;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.LinearLayout;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import me.shurufa.R;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.ShareConstants;
import me.shurufa.utils.SinaShareManager;
import me.shurufa.utils.Utils;

/**
 * 作者 : andy
 * 日期 : 16/3/27 17:47
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 分享
 */
public class ShareController implements IUiListener {

    public IWXAPI mWxApi;

    public Tencent mTencent;

    public String mLocalPath; // qq qzone用

    /*public static void initShare(Context context) {
        mWxApi = WXAPIFactory.createWXAPI(context, ShareConstants.WX_ID);
        mWxApi.registerApp(ShareConstants.WX_ID);
        //mTencent = Tencent.createInstance(ShareConstants.QQ_ID, context);
    }*/

    public ShareController(Context context) {
        mWxApi = WXAPIFactory.createWXAPI(context, ShareConstants.WX_ID);
        mWxApi.registerApp(ShareConstants.WX_ID);
    }

    /**
     * 微信分享
     * @param flag(0:分享到微信好友，1：分享到微信朋友圈)
     */


    public void shareToWeChat(int flag, String url, String title, String desc, Bitmap bitmap){
        Bitmap bm = null;
        WXImageObject imgObj = null;
        float bWidth = bitmap.getWidth();
        float bHeight = bitmap.getHeight();
        float size = bitmap.getHeight()*bitmap.getWidth()*2.0f/(1024.0f*1024.0f);
        Matrix matrix = null;
        if (size>9.0&&flag==1){
            matrix = new Matrix();
            float scaleWidth = 1.0f/3.0f;
            float scaleHeight = 1.0f/3.0f;
            matrix.postScale(scaleWidth,scaleHeight);
            while (size>9) {
                bm = Bitmap.createBitmap(bitmap,0,0,(int)bWidth,(int)bHeight,matrix,true);
                bWidth = bm.getWidth();
                bHeight = bm.getHeight();
                size = bWidth*bHeight*2/(1024*1024);
                bitmap = bm;
            }

            imgObj = new WXImageObject(bm);
        }else {
            imgObj = new WXImageObject(bitmap);
        }

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, Constants.THUMB_SIZE, Constants.THUMB_SIZE, true);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        thumbBmp.compress(Bitmap.CompressFormat.PNG, 80, stream);

        if (stream.toByteArray().length>32*1024){
            int bmpLen = bitmap.getWidth()*bitmap.getHeight()*4;
            double ratio = Math.sqrt( (32*1024)/(double)(bmpLen) );
            int width = (int)(ratio*bitmap.getWidth());
            int height =(int)(ratio*bitmap.getHeight());
            thumbBmp = Bitmap.createScaledBitmap(bitmap, width, height, true);
            thumbBmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            msg.thumbData = stream.toByteArray();
        }else {
            byte[] byteArray = stream.toByteArray();
            msg.thumbData = byteArray;
            Log.d("ByteLength", byteArray.length + "");
        }
        bitmap.recycle();
        /* WeixiShareUtil.bmpToByteArray(thumbBmp, true); */ //设置缩略图


        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.transaction = "image";
        req.scene = flag==0?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
        //0分享到微信好友
        //1分享到微信朋友圈
        if (flag == 0) {
            req.message.title= System.currentTimeMillis() + ".jpg";
        }
        Global.mWxApi.sendReq(req);
        thumbBmp.recycle();
    }

    private KProgressHUD kProgressHUD;
    public void shareToWeibo(final Activity context, final LinearLayout viewGroup) {
        if (kProgressHUD == null) {
            kProgressHUD = KProgressHUD.create(context);
        }
        kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在生成长图...")
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = ScreenShot.compressImage(ScreenShot.getBitmapByView(viewGroup), 300);
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (kProgressHUD != null) {
                            kProgressHUD.dismiss();
                            kProgressHUD = null;
                        }

                        SinaShareManager manager = new SinaShareManager();
                        manager.registSina(context);
                        ShareContentPic contentPic = new ShareContentPic(bitmap);
                        manager.shareBySina(contentPic, context);
                        System.gc();
                    }
                });
            }
        }).start();
    }

    public void shareToQQ(final Activity context, final LinearLayout viewGroup) {

        if (kProgressHUD == null) {
            kProgressHUD = KProgressHUD.create(context);
        }
        kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在生成长图...")
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = ScreenShot.compressImage(ScreenShot.getBitmapByView(viewGroup), 300);

                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    if (TextUtils.isEmpty(mLocalPath)) {
                        mLocalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                    }
                }

                final File f = new File(mLocalPath, System.currentTimeMillis()+ ".jpg");
                if (f.exists()) {
                    f.delete();
                }
                try {
                    FileOutputStream out = new FileOutputStream(f);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (kProgressHUD != null) {
                            kProgressHUD.dismiss();
                            kProgressHUD = null;
                        }

                        Bundle params = new Bundle();
                        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
                        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, f.getAbsolutePath());
                        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, context.getString(R.string.app_name));
                        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
                        mTencent = Tencent.createInstance(ShareConstants.QQ_ID, context);
                        mTencent.shareToQQ(context, params, new IUiListener() {
                            @Override
                            public void onComplete(Object o) {
                                bitmap.recycle();
                                f.delete();
                                Utils.showToast("分享成功");
                                System.gc();
                            }

                            @Override
                            public void onError(UiError uiError) {
                                bitmap.recycle();
                                System.gc();
                            }

                            @Override
                            public void onCancel() {
                                bitmap.recycle();
                                System.gc();
                            }
                        });
                    }
                });
            }
        }).start();

    }

    public void shareToQZone(final Activity context, final LinearLayout viewGroup){
        if (kProgressHUD == null) {
            kProgressHUD = KProgressHUD.create(context);
        }
        kProgressHUD.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在生成长图...")
                .setCancellable(false)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = ScreenShot.compressImage(ScreenShot.getBitmapByView(viewGroup), 300);

                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    if (TextUtils.isEmpty(mLocalPath)) {
                        mLocalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                    }
                }

                final File f = new File(mLocalPath, System.currentTimeMillis()+ ".jpg");
                if (f.exists()) {
                    f.delete();
                }
                try {
                    FileOutputStream out = new FileOutputStream(f);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (kProgressHUD != null) {
                            kProgressHUD.dismiss();
                            kProgressHUD = null;
                        }

                        Bundle params = new Bundle();
                        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
                        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, f.getAbsolutePath());
                        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, context.getString(R.string.app_name));
                        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
                        mTencent = Tencent.createInstance(ShareConstants.QQ_ID, context);
                        mTencent.shareToQQ(context, params, new IUiListener() {
                            @Override
                            public void onComplete(Object o) {
                                Utils.showToast("分享成功");
                                f.delete();
                                bitmap.recycle();
                                System.gc();
                            }

                            @Override
                            public void onError(UiError uiError) {
                                bitmap.recycle();
                                System.gc();
                            }

                            @Override
                            public void onCancel() {
                                bitmap.recycle();
                                System.gc();
                            }
                        });
                    }
                });
            }
        }).start();
    }


    /**
     * QQ的
     * @param o
     */
    @Override
    public void onComplete(Object o) {
        Utils.showToast("分享成功");
    }

    /**
     * QQ的
     * @param uiError
     */
    @Override
    public void onError(UiError uiError) {

    }

    /**
     * QQ的
     */
    @Override
    public void onCancel() {

    }
}
